package mobile

import (
	"net/http"
	"strings"
	"time"

	"gitee.com/cxssang/goframe/lib/crypto"

	"gitee.com/cxssang/goframe/lib/utils"

	"gitee.com/cxssang/goframe/lib/sql"

	. "gitee.com/cxssang/genealogy/act"
)

func init() {
	HandleFunMap["/m/login"] = func(w http.ResponseWriter, r *http.Request) {
		switch r.Method {
		case "GET":
			name, _ := sql.New().Select("setting", sql.NewWhere().Add("key='name'"), 0, 0, "value", "").FetchOne()
			if name == nil {
				name = &sql.Row{}
				name.Set("value", "族谱系统")
			}
			DisplayM(w, r, "mobile/login", map[string]interface{}{
				"title": "登录",
				"name":  name.Get("value"),
			})
		case "POST":
			name := r.PostFormValue("name")
			id := r.PostFormValue("id")
			if name == "" && id == "" {
				DisplayError(w, "请输入用户名")
				return
			}
			password := r.PostFormValue("password")
			if password == "" {
				DisplayError(w, "请输入密码")
				return
			}
			sq := sql.New()
			where := sql.NewWhere()
			if id != "" {
				where.Add("id=?", id)
			} else if name != "" {
				where.Add("name=?", name)
			}
			where.Add("password=?", utils.Md5(password))
			users, err := sq.Select("users", where, 0, 0, "id,name,member_id", "id desc").FetchAll()
			if err != nil {
				DisplayError(w, err.Error())
				return
			}
			if users.Len() == 0 {
				DisplayError(w, "用户名或密码错误")
				return
			}
			if users.Len() > 1 {
				var memberIds []interface{}
				for _, user := range users {
					memberIds = append(memberIds, user.Get("member_id"))
				}
				symbols := strings.Repeat("?,", len(users))
				symbols = symbols[:len(symbols)-1]
				where = sql.NewWhere().Add("a.id in ("+symbols+")", memberIds...)
				members, err := sq.Raw("select a.id,a.parent_id,b.name as parent_name from members a left join members b on(b.id=a.parent_id) where ").Concat(where.String()).SetParams(where.GetParams()...).FetchAll()
				if err != nil {
					DisplayError(w, err.Error())
					return
				}
				for _, user := range users {
					for _, member := range members {
						if member.Get("id") == user.Get("member_id") {
							user.Set("parent_id", member.Get("parent_id"))
							user.Set("parent_name", member.Get("parent_name"))
						}
					}
				}
				DisplayM(w, r, "mobile/moreUsers", map[string]interface{}{
					"users":    users,
					"password": password,
					"title":    "选择用户",
				})
				return
			}
			aes := crypto.NewAes()
			authKey := aes.Encrypt(users.Get(0).Get("id"), string(K))
			http.SetCookie(w, &http.Cookie{
				Name:     "m-auth-key",
				Value:    authKey,
				Expires:  time.Now().AddDate(1, 0, 0),
				HttpOnly: true,
			})
			http.Redirect(w, r, "/m/index", http.StatusFound)
		}
	}

	HandleFunMap["/m/rename"] = func(w http.ResponseWriter, r *http.Request) {
		if r.Method == "POST" {
			id := r.FormValue("id")
			newName := r.FormValue("newName")
			password := r.FormValue("password")
			if id == "" || newName == "" || password == "" {
				JsonError(w, "参数错误")
				return
			}
			sq := sql.New()
			count, _ := sq.Count("users", sql.NewWhere().Add("name=?", newName), "id")
			if count > 0 {
				JsonError(w, "新用户名已存在")
				return
			}
			where := sql.NewWhere().Add("id=?", id).Add("password=?", utils.Md5(password))
			user, err := sq.Select("users", where, 0, 0, "*", "").FetchOne()
			if err != nil {
				JsonError(w, err.Error())
				return
			}
			if user == nil {
				JsonError(w, "用户名或密码不正确")
				return
			}
			_, err = sq.Update("users", where, map[string]interface{}{
				"name": newName,
			}).Exec()
			if err != nil {
				JsonError(w, err.Error())
				return
			}
			JsonSuccess(w, nil)
		}
	}

	HandleFunMap["/m/logout"] = func(w http.ResponseWriter, r *http.Request) {
		http.SetCookie(w, &http.Cookie{
			Name:    "m-auth-key",
			Value:   "",
			Expires: time.Now().AddDate(-1, 0, 0),
		})
		http.Redirect(w, r, "/m/login", http.StatusFound)
	}
}
